package com.machine.dao.order.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.machine.bean.PriceOrder;
import com.machine.dao.order.PriceOrderDao;

@Component("priceOrderDao")
@Transactional
public class PriceOrderDaoImpl implements PriceOrderDao {
	
	private SessionFactory sessionfactory;
	
	public SessionFactory getSessionfactory() {
		return sessionfactory;
	}

	@Resource
	public void setSessionfactory(SessionFactory sessionfactory) {
		this.sessionfactory = sessionfactory;
	}

	@Override
	public int add(PriceOrder priceOrder) {
		this.sessionfactory.getCurrentSession().save(priceOrder);
		return 1;
	}

	@Override
	public int delete(PriceOrder priceOrder) {
		this.sessionfactory.getCurrentSession().delete(priceOrder);
		return 1;
	}

	@Override
	public PriceOrder find(PriceOrder priceOrder) {
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<PriceOrder> findAll(String providerName,String buyName,int offset, int length) {
		String hql= "from PriceOrder priceOrder where priceOrder.providerName = '" + providerName + "' OR priceOrder.buyName= '"+buyName+"'";
		Session session = sessionfactory.getCurrentSession();
		
		Query query = session.createQuery(hql);
		query.setFirstResult(offset);  
        query.setMaxResults(length);  
        
		List<PriceOrder> list = query.list();
		
		System.out.println("list size :" + list.size());
		if(list.size() > 0){
			return list;
		}
		return null;
	}

	@Override
	public int update(PriceOrder priceOrder) {
		this.sessionfactory.getCurrentSession().update(priceOrder);
		return 1;
	}

	@Override
	public int deleteByIdList(List<Integer> list) {
		PriceOrder priceOrder = null;
		for(int id : list){
			priceOrder = new PriceOrder();
			priceOrder.setId(id);
			this.sessionfactory.getCurrentSession().delete(priceOrder);
		}
		return 1;
	}

	@Override
	public PriceOrder findById(Integer id) {
		String hql = "from PriceOrder priceOrder where priceOrder.id ="
			+ id + " ";
		Session session = sessionfactory.getCurrentSession();
		Query query = session.createQuery(hql);
		List<PriceOrder> orderList = query.list();
		if (orderList.size() > 0) {
			return orderList.get(0);
		}
		return null;
	}

	@Override
	public int getAllRowCount(String hql) {
		Session session = sessionfactory.getCurrentSession();
		Query query = session.createQuery(hql);  
		List list = query.list();  
		System.out.println("cout : " + list.size());
		return list.size();
	}

}
